﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class PhysicSystem : MonoBehaviour {
    public static PhysicSystem Instance;
    private List<PhysicCollider> colliders = new List<PhysicCollider>();
    private List<PhysicContact> contacts = new List<PhysicContact>();
    private PhysicSolver solver;
    private List<PlayerController> playerControllers = new List<PlayerController>();

    private void Awake()
    {
        Instance = this;
        solver = new PhysicSolver();
    }

    public void AddCollider(PhysicCollider collider)
    {
        colliders.Add(collider);
    }
    public void AddController(PlayerController cont)
    {
        playerControllers.Add(cont);
    }


    private void FixedUpdate()
    {
        foreach(var c in playerControllers)
        {
            c.UpdatePhysic();
        }

        contacts.Clear();
        foreach(var c in colliders)
        {
            c.solverWorkArea.Clear();
            c.IsCollision = false;
        }

        foreach(var c in colliders)
        {
            c.AccumulateForces();
        }
        foreach(var c in colliders)
        {
            c.UpdatePosition();
        }

        for(var i = 0; i < colliders.Count; i++)
        {
            for(var j = i+1; j < colliders.Count; j++)
            {
                PhysicContact contact;
                if(PhysicCollision.Detect(colliders[i], colliders[j], out contact))
                {
                    contacts.Add(contact);
                }
            }
        }
        foreach(var c in contacts)
        {
            c.A.IsCollision = true;
            c.B.IsCollision = true;
        }

        foreach(var c in contacts)
        {
            solver.Constraint(c);
        }

        foreach(var c in colliders)
        {
            c.Clear();
        }
    }
}
